package com.weiya.system.error;

import com.weiya.response.ResponseUtil;
import com.weiya.response.ResponseVo;
import netscape.security.ForbiddenTargetException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.DataAccessException;
import org.springframework.expression.AccessException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * <p class="detail">
 * 功能:全局异常处理,所有的异常都放在这里进行处理,无需在每个地方try catch
 * </p>
 *
 * @author BaoWeiwei
 * @ClassName Exception advice.
 * @Version V1.0.
 * @date 2018.07.27 13:31:59
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

	private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
//
//	/**
//	 * 处理参数异常
//	 * @param e
//	 * @return
//	 */
	@ExceptionHandler(MethodArgumentNotValidException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public ResponseVo handleMethodArgumentNotValidException(Exception e){
		return ResponseUtil.error(400,"参数验证失败");
	}
//
	@ResponseStatus(HttpStatus.UNAUTHORIZED)
	@ExceptionHandler(UnauthorizedException.class)
	public ResponseVo handleNotAuthorizedException(Exception e) {
		logger.error(e.getMessage(), e);
		return ResponseUtil.error(e.getLocalizedMessage());
	}
//
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	@ExceptionHandler(DataAccessException.class)
	public ResponseVo handleDataAccessException(Exception e) {
		logger.warn(e.getMessage(), e);
		return ResponseUtil.error("数据访问错误: " + e.getLocalizedMessage());
	}

	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	@ExceptionHandler(AccessException.class)
	public ResponseVo handleHttpAccessException(Exception e) {
		logger.warn(e.getMessage(), e);
		return ResponseUtil.error("访问外部服务错误: " + e.getLocalizedMessage());
	}

	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	@ExceptionHandler(Exception.class)
	public ResponseVo handleException(Exception e) {
		logger.warn(e.getMessage(), e);
		return ResponseUtil.error("系统内部错误: " + e.getLocalizedMessage());
	}


	/**
	 * 没有权限——shiro
	 * @param e
	 * @return
	 */
//	@ExceptionHandler(UnauthorizedException.class)
//	@ResponseStatus(HttpStatus.FORBIDDEN)
//	public ResponseVo handleUnauthorizedException(UnauthorizedException e){
//		return ResponseUtil.error(403,"没有权限");
//	}
}
